package com.xuwangcheng.viewer;

import java.util.ArrayList;
import java.util.List;

/**
 * 如何使用普通的方法实现观察者模式?
 * <br>感觉两种方式是差不多
 * @author xuwangcheng
 *
 */
public class CommonTest {
	public static void main(String[] args) {
		HouseV h = new HouseV(3000000.0);
		h.getViewers().add(new HousePriceObserverV("小刚"));
		h.getViewers().add(new HousePriceObserverV("小红"));
		h.getViewers().add(new HousePriceObserverV("小明"));
		
		h.setPrice(3500000.0);
	}	
}

class HouseV {
	private Double price;
	private List<HouseViewer> viewers = new ArrayList<HouseViewer>();
	
	
	public HouseV(double price) {
		// TODO Auto-generated constructor stub
		super();
		this.price = price;
	}
	
	public void setPrice(Double price) {
		if (price != this.price) {
			for (HouseViewer viewer:viewers) {
				viewer.view(this, price);
			}
		}
		this.price = price;
	}
	
	
	public void setViewers(List<HouseViewer> viewers) {
		this.viewers = viewers;
	}
	
	public List<HouseViewer> getViewers() {
		return viewers;
	}
	
	public Double getPrice() {
		return price;
	}
}

interface HouseViewer {
	void view(HouseV h, double price);
}

class HousePriceObserverV implements HouseViewer {
	private String name;

	public HousePriceObserverV(String name) {
		// TODO Auto-generated constructor stub
		super();
		this.name = name;
	}
	
	@Override
	public void view(HouseV h, double price) {
		// TODO Auto-generated method stub
		System.out.println(this.name + "知晓了房价已经变化了,最新价格为:" + price);
	}
	
}
